package org.homly.admin.tag.product;

import java.util.HashMap;
import java.util.List;

import javax.servlet.jsp.JspException;
import javax.servlet.jsp.tagext.TagSupport;

import org.homly.sql.SQLTool;

@SuppressWarnings("serial")
public class ProductListTag extends TagSupport {

	private String name = "rows";
	private String typeId = null;
	private String brandName = null;
	private String status = null;
	private String pageMax = "999999";

	@Override
	public int doStartTag() throws JspException {

		String pageIndex = pageContext.getRequest().getParameter("pageIndex");
		int page = 1;
		if (pageIndex != null && !pageIndex.equals("")) {
			page = Integer.parseInt(pageIndex);
		}
		List<HashMap<String, String>> list = null;
		int totalCount = 0;
		try {
			String where = null;
			if (status != null && !"".equals(status)) {
				where = " where product_status=" + status + " AND config_id IN (SELECT config_id FROM config WHERE config_status=" + status + ") ";
			} else {
				where = " where 1=1 ";
			}
			if(typeId != null && typeId.matches("\\d+")) {
				where += " and config_id=" + typeId;
			}
			if(brandName != null && !brandName.equals("")) {
				where += " and product_brand_name='" + brandName + "' ";
			}
			list = SQLTool.query(" select * ", " from product ",
					where,
					" order by product_sort_no desc ", "product_sort_no", Integer.valueOf(pageMax),
					page);
			List<HashMap<String, String>> totalList = SQLTool
					.query("select count(*) as totalCount from product" + where);

			if (totalList != null && totalList.size() > 0) {
				String totalStr = ((HashMap<String, String>) totalList.get(0))
						.get("totalCount");
				if (totalStr != null && !totalStr.equals("")) {
					totalCount = Integer.parseInt(totalStr);
				}
			}
		} catch (Exception e) {
			e.printStackTrace();
		}

		pageContext.setAttribute(name, list);
		pageContext.setAttribute("pageIndex", page);
		pageContext.setAttribute("totalCount", totalCount);
		return super.doStartTag();
	}

	public void setName(String name) {
		this.name = name;
	}
	public void setTypeId(String typeId) {
		this.typeId = typeId;
	}
	public void setBrandName(String brandName) {
		this.brandName = brandName;
	}
	public void setStatus(String status) {
		this.status = status;
	}
	public void setPageMax(String pageMax) {
		this.pageMax = pageMax;
	}

}
